package com.xieh.webmagic.magic;

import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.List;

/**
 * @author 谢辉
 * @Classname UserProcessor
 * @Description TODO
 * @Date 2020/11/20 16:04
 */
@Component
public class UserProcessor implements PageProcessor {

    @Override
    public void process(Page page) {
        List<String> targetRequests = page.getHtml().links().regex("https://blog.csdn.net/[a-z 0-9 _]+/article/details/[0-9]{8}").all();

        // 添加目标地址，从一个页面爬到另一个页面
        page.addTargetRequests(page.getHtml().links().regex("https://blog.csdn.net/[a-z 0-9 _]+/article/details/[0-9]{8}").all());

        System.out.println("UserProcessor:添加目标地址，从一个页面爬到另一个页面:" + targetRequests.toString());

        // 添加字段，代码结构化，可多次使用
        String nickName = page.getHtml().xpath("//*[@id=\"uid\"]/text()").get();
        String image = page.getHtml().xpath("//*[@id=\"asideProfile\"]/div[1]/div[1]/a/img[1]/@src").get();
        if (nickName != null && image != null){
            page.putField("nickName",nickName);
            page.putField("image",image);
        } else {
            // 不执行后面的步骤
            page.setSkip(true);
        }
    }

    @Override
    public Site getSite() {
        return Site.me()
                .setSleepTime(100)
                .setRetryTimes(3)
                .setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31");
    }
}